/**
 * 招聘负责人接收
 * */
import React, { useRef, useState, useEffect } from 'react';
import { Form, Button, Divider, Row, Col, message, Avatar } from 'antd';
import { withRouter } from 'umi';
import { PageContainer } from '@/molecules';
import { BottomAction } from '@/components';
import { useRequest, defaultFormatResult } from '@/hooks';
import { PreviewModal } from '@/pages/EntryManage/components/Preview';
import { history } from 'umi';
import EmployeeCard from '@/pages/EntryManage/components/EmployeeCard';
import { queryCandidateProcess } from '@/pages/EntryManage/services';
import { size } from 'lodash';
import { replaceToWaitEntry } from '@/pages/EntryManage/utils';
import Card from '../components/Card';
import styles from './index.less';
import { getSoft } from '../services';
import SoftwarePreinstall from './component/SoftwarePreinstall';
import { getEquipment, getSoftSelected, getReceiveByHR } from './services';

const formLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
        md: { span: 4 },
        xl: { span: 2 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
        md: { span: 16 },
        xl: { span: 10 }
    }
};

const Index = ({ location, form }) => {
    const { validateFieldsAndScroll } = form;
    const [photoData, setPhotoData] = useState();
    const [softTableData, setSoftTableData] = useState([]);
    const [entryStatus, setEntryStatus] = useState(undefined);
    const [entryStep, setEntryStep] = useState(undefined);
    const [, setDefaultOrganizationName] = useState(null);

    // 招聘负责人接收
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const { employeeCode } = user;
    const { entryPersonnelCode } = location.query;
    const previewRef = useRef();
    // 提交
    const { loading: receiveByHRLoading, run: fetchReceiveByHR } = useRequest(value => getReceiveByHR(value), {
        manual: true,
        onSuccess: res => {
            if (res) {
                const { code, msg } = res;

                if (code === 10000) {
                    history.push({
                        pathname: '/office/personnelManagement/onboardAndLeave/entryManage/waitEntry'
                    });
                    message.success(msg);
                } else {
                    message.error(msg);
                }
            }
        }
    });

    // 请求数据
    const { run: fetchCandidateProcess } = useRequest(() => queryCandidateProcess(entryPersonnelCode), {
        manual: true,
        onSuccess: res => {
            const { data, code, msg } = res;
            if (code === 10000) {
                const {
                    idPhoto,
                    entryStatus: entryStatusData,
                    step,
                    assignEmployeeList,
                    defaultEntryProcessOrganizationName
                } = data;
                setPhotoData(idPhoto[0]);
                setEntryStatus(entryStatusData);
                setEntryStep(step);
                setDefaultOrganizationName(defaultEntryProcessOrganizationName);
                if (entryStatusData) {
                    if (employeeCode) {
                        const result = assignEmployeeList.filter(item => item.employeeCode === employeeCode);
                        if (!result.length) {
                            replaceToWaitEntry('您不是当前节点处理人');
                        }
                    }
                }
            } else {
                message.error(msg);
            }
        }
    });
    // 获取通用软件
    const { data: softList, run: fetchSoft } = useRequest(() => getSoft({ entryPersonnelCode }), {
        manual: true,
        ...defaultFormatResult
    });
    // 获取已选择软件
    const { loading: softLoading, data: softSelectedList, run: fetchSoftSelected } = useRequest(
        () => getSoftSelected({ entryPersonnelCode, choiceType: 0 }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );
    // 获取设备
    const { loading: deviceDataLoading, data: deviceData, run: fetchEquipment } = useRequest(
        () => getEquipment({ entryPersonnelCode, choiceType: '' }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    const { computerType, needDisplay, systemType, needMouse } = size(deviceData) > 0 ? deviceData[0] : {};

    const handlePreview = source => {
        const { keyName, url, originName } = source || {};
        previewRef.current.open({
            type: 'image',
            title: keyName,
            origin: url,
            originName
        });
    };

    // 接收新员工
    const handleSubmit = () => {
        validateFieldsAndScroll({ scroll: { alignWithTop: true } }, err => {
            const param = {
                currentHandlerEmployeeCode: employeeCode,
                entryPersonnelCode
            };

            if (!err) {
                fetchReceiveByHR(param);
            }
        });
    };
    useEffect(() => {
        fetchEquipment();
        fetchSoft();
        fetchSoftSelected();
        fetchCandidateProcess();
    }, [fetchCandidateProcess, fetchEquipment, fetchSoft, fetchSoftSelected]);
    useEffect(() => {
        if (size(softList) > 0) {
            // 将数据源进行分类
            setSoftTableData(softList.filter(item => item.softClass === 0));
        }
    }, [softList]);
    return (
        <PageContainer>
            <EmployeeCard employeeCode={entryPersonnelCode} isShowControls={false} style={{ marginBottom: '20px' }} />

            <Divider />
            <Form {...formLayout}>
                <Card
                    title="个人档案"
                    headBorder
                    bordered={false}
                    extra={
                        entryStatus === 1 && entryStep === 2 ? (
                            <BottomAction>
                                <span className={styles.autoNotice}>自行通知部门准备</span>
                                <Button type="primary" onClick={handleSubmit} loading={receiveByHRLoading}>
                                    接收
                                </Button>
                            </BottomAction>
                        ) : null
                    }
                >
                    <Form.Item label="档案信息">
                        <Row type="flex" style={{ lineHeight: '40px' }}>
                            <Col>
                                <a
                                    onClick={() => {
                                        const param = { entryPersonnelCode };
                                        history.push({
                                            pathname:
                                                '/office/personnelManagement/onboardAndLeave/entryManage/entryEmployeeDetail',
                                            query: param
                                        });
                                    }}
                                >
                                    查看档案
                                </a>
                            </Col>
                        </Row>
                    </Form.Item>
                    <Form.Item label="证件照">
                        <div>
                            <Avatar src={photoData?.url} shape="square" size={64} />

                            {size(photoData?.url) > 0 ? (
                                <>
                                    <a href="#" onClick={() => handlePreview(photoData)} style={{ marginLeft: '15px' }}>
                                        预览
                                    </a>
                                    <a href={photoData?.url} style={{ marginLeft: '10px' }}>
                                        下载
                                    </a>
                                </>
                            ) : null}
                        </div>
                        <PreviewModal title ref={previewRef} height="650px" />
                    </Form.Item>
                </Card>
                <Divider />
                <Card
                    title="电脑偏好"
                    headBorder
                    bordered={false}
                    className={styles.cardBox}
                    loading={deviceDataLoading}
                >
                    <Row>
                        <Col span={12}>
                            <ul className={styles.materialList}>
                                <li>
                                    <span>电脑类型：</span>
                                    {computerType === 0 && <span>笔记本电脑</span>}
                                    {computerType === 1 && <span>台式整机</span>}
                                </li>
                                <li>
                                    <span>需要显示器：</span>
                                    {needDisplay === 0 && <span>否</span>}
                                    {needDisplay === 1 && <span>是</span>}
                                </li>
                            </ul>
                        </Col>
                        <Col span={12}>
                            <ul className={styles.materialList}>
                                <li>
                                    <span>系统类型：</span>
                                    {systemType === 0 && <span>windows</span>}
                                    {systemType === 1 && <span>Mac os</span>}
                                    {systemType === 2 && <span>Linux</span>}
                                </li>
                                <li>
                                    <span>需要鼠标：</span>
                                    {needMouse === 0 && <span>否</span>}
                                    {needMouse === 1 && <span>是</span>}
                                </li>
                            </ul>
                        </Col>
                    </Row>
                </Card>
                <Divider />
                <Card title="预装软件" headBorder bordered={false} className={styles.cardBox} loading={softLoading}>
                    <SoftwarePreinstall selected={softSelectedList} tableData={softTableData} />
                </Card>
                <div style={{ height: '50px' }}></div>
            </Form>
        </PageContainer>
    );
};
export default withRouter(Form.create()(Index));
